<template>
  <el-form-item :label-width="item.labelWidth?item.labelWidth:'130px'" :label="item.title">
    <span slot="label">{{item.title}}
        <el-tooltip v-if="item.info" :content="item.info" placement="top">
          <span class="fas fa-info-circle color"></span>
        </el-tooltip>
      </span>
    <el-checkbox-group v-model="formRoles" :disabled="disabled" placeholder="请选择角色" class="role-select" @change="handleRoleChange">
      <el-checkbox :label="i.roleName"  v-for="i in list" :key="i.roleId" ></el-checkbox>
    </el-checkbox-group>
  </el-form-item>

</template>
<style>
.role-select {
  width: 100%;
}
.el-checkbox {
  margin-left: 30px;
}
</style>

<script>
import { getRoles, useIdGetRoles } from '../../../api/common';
export default {
  data() {
    return {
      list: [],
      userRoles: [],
      formRoles: []
    };
  },
  props: ['item', 'form', 'userId', 'rules', 'disabled'],
  mounted: function() {
    if (this.form.userId) {
      this.userId = this.form.userId;
    }
    if (this.userId) {
      useIdGetRoles(this.userId).then(response => {
        this.form.roles = [];
        this.userRoles = response.data;
        this.list = this.userRoles;
        this.userRoles.forEach(v => {
          if (v.checked === 1) {
            this.formRoles.push(v.roleName);
            this.form.roles.push({
              roleId: v.roleId
            });
          }
        });
        // console.log(this.formRoles)
        // console.log(this.form)
      });
    } else {
      getRoles()
        .then(response => {
          // console.log(response)
          const data = response.data;
          this.list = data;
          this.userRoles = data;
        })
        .catch(response => {
          // console.log(response);
        });
    }
  },
  methods: {
    handleRoleChange: function(value) {
      this.form.roles = [];
      value.forEach(i => {
        this.userRoles.forEach(j => {
          if (i === j.roleName) {
            this.form.roles.push({
              roleId: j.roleId
            });
          }
        });
      });
      // console.log(this.form.roles)
    }
  }
};
</script>

